package com.sunwayworld.common.io;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;

public class FileUtils {

	public static String readFile(File file) {
		String fileContent = null;
		FileInputStream fis = null;
		FileChannel fc = null;
		try {
			fis = new FileInputStream(file);
			fc = fis.getChannel();

			ByteBuffer bb = ByteBuffer.allocate((int) fc.size() + 1);

			fc.read(bb);
			bb.flip();
			fileContent = new String(bb.array());

		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			// release the FileChannel
			try {
				fc.close();
			} catch (Exception ex) {

			}
			try {
				fis.close();
			} catch (Exception ex) {

			}
		}

		// write out the contents of this file
		return fileContent;

	}

	public static String readFile(String filePath) {
		File fileName = new File(filePath);
		String fileContent = null;
		FileInputStream fis = null;
		FileChannel fc = null;
		try {
			fis = new FileInputStream(fileName);
			fc = fis.getChannel();

			ByteBuffer bb = ByteBuffer.allocate((int) fc.size() + 1);

			fc.read(bb);
			bb.flip();
			fileContent = new String(bb.array());

		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			// release the FileChannel
			try {
				fc.close();
			} catch (Exception ex) {

			}
			try {
				fis.close();
			} catch (Exception ex) {

			}
		}

		// write out the contents of this file
		return fileContent;

	}

	public static void writeFile(String filePath, String str) {

		FileOutputStream fo = null;

		try {
			File file = new File(filePath);
			if (!file.exists()) {
				file.createNewFile();
			}
			fo = new FileOutputStream(file);
			fo.write(str.getBytes());
			fo.flush();
			fo.close();

		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			try {
				fo.close();
			} catch (Exception ex) {

			}

		}

	}
}